package cn.tarena.ht.shiro;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import cn.tarena.ht.pojo.User;
import cn.tarena.ht.service.UserService;

public class AuthRealm extends AuthorizingRealm{
	@Autowired
	private UserService userService;

	//权限认证
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		//获取用户真实信息
		User user = (User)SecurityUtils.getSubject().getPrincipal();
		//通过用户ID查询用户的真实权限信息
		List<String> pList = userService.findPrivilegeList(user.getUserId());
		//为权限控制提供真实权限数据
		AuthorizationInfo info = new SimpleAuthorizationInfo();
		return info;
	}
	
	//登陆认证
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//转换令牌的数据类型
		UsernamePasswordToken loginToken = (UsernamePasswordToken) token;
		//获取用户名
		String username = loginToken.getUsername();
		System.out.println(loginToken.getPassword());
		//通过用户名，查询用户信息
		User user = userService.findUserByUsername(username);
		System.out.println(user.getUsername());
		System.out.println(user.getPassword());
		//将查询到得真实信息返回给Shiro安全中心
		AuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
		return info;
	}

}
